package com.kzd.btgame.main.game

import android.annotation.SuppressLint
import android.net.Uri
import android.view.LayoutInflater
import android.view.View
import android.widget.CheckBox
import androidx.annotation.DrawableRes
import androidx.fragment.app.Fragment
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.AppUtils
import com.blankj.utilcode.util.BarUtils
import com.google.android.exoplayer2.MediaItem
import com.google.android.exoplayer2.Player.REPEAT_MODE_ALL
import com.google.android.exoplayer2.SimpleExoPlayer
import com.kzd.btgame.R
import com.kzd.btgame.app.AppFlowBus
import com.kzd.btgame.app.GTApplication
import com.kzd.btgame.app.GT_CHANNEL
import com.kzd.btgame.app.GT_CHANNEL_DEFAULT
import com.kzd.btgame.callback.AppPagerAdapter
import com.kzd.btgame.custom.setOnClickAntiShakeListener
import com.kzd.btgame.databinding.ActivityGameDetailsBinding
import com.kzd.btgame.db.Download
import com.kzd.btgame.db.GameDownload
import com.kzd.btgame.entity.GameDetails
import com.kzd.btgame.manage.DownloadManager
import com.kzd.btgame.jetpack.vm.GameViewModel
import com.kzd.btgame.main.*
import com.kzd.btgame.main.game.adapter.GameListLabelAdapter
import com.module.lemlin.http.Status
import com.module.lemlin.http.msg
import com.module.lemlin.image.loadImage
import com.module.lemlin.owner.OwnerViewBindingActivity
import com.module.lemlin.owner.ownerViewModel
import java.lang.Exception


class GameDetailsActivity : OwnerViewBindingActivity<ActivityGameDetailsBinding>() {

    companion object {
        private val tabs = arrayOf("详情", "福利", "开服", "评论", "交易")
    }

    private val mAppPagerAdapter: AppPagerAdapter by lazy {
        object : AppPagerAdapter(supportFragmentManager, tabs) {

            private val fragments = mutableListOf(
                GameDetailsFragment.newInstance(), GameWelfareFragment.newInstance(),
                GameServiceFragment.newInstance(), GameDiscussFragment.newInstance(),
                GameBargainFragment.newInstance()
            )

            override fun fragment(position: Int): Fragment = fragments[position]
        }
    }

    private val mGameId: String
        get() = intent.extras?.getString(KEY_GAME_DETAILS_ID) ?: ""

    private val mAction: Int
        get() = try {
            (intent.extras?.getString(KEY_GAME_DETAILS_INDEX) ?: "0").toInt()
        } catch (e: Exception) {
            0
        }

    private val mGameDownload: GameDownload?
        get() = GTApplication.appDatabase.gameDownloadDao()
            .selectGameDownloadByGameID(mGameId)

    private val mDownloadManager by lazy {
        DownloadManager.instance
    }

    private var mSimpleExoPlayer: SimpleExoPlayer? = null

    private val mViewModel: GameViewModel by lazy {
        ownerViewModel(owner = this)
    }

    override val inflate: (LayoutInflater) -> ActivityGameDetailsBinding
        get() = ActivityGameDetailsBinding::inflate

    override fun initView() {

        BarUtils.addMarginTopEqualStatusBarHeight(mViewBinding.tbGameDetailsBar)

        mViewBinding.ivGameDetailsBack.setOnClickListener {
            finish()
        }

        mViewBinding.tabGameDetailsKind.apply {
            for (item in tabs) {
                addTab(newTab().setText(item))
            }
        }.setupWithViewPager(mViewBinding.vpGameDetailsBody.apply {
            adapter = mAppPagerAdapter
        })

        mViewBinding.tabGameDetailsKind.getTabAt(mAction)?.select()

        //分享
        mViewBinding.ivGameDetailsShare.setOnClickAntiShakeListener {
            val gameDetails = mViewModel.gameDetailsLiveData.value
                ?.data?.data ?: return@setOnClickAntiShakeListener
            mViewModel.userShare(
                activity = this,
                url = gameDetails.fenxiang,
                title = gameDetails.name ?: "",
                desc = gameDetails.summary ?: ""
            )
        }
        //收藏
        mViewBinding.tvGameDetailsCollect.setOnClickAntiShakeListener {
            val isCollect = mViewModel.gameDetailsLiveData.value
                ?.data?.data?.shoucang ?: 0
            if (isCollect == 0) checkLogin {
                mViewModel.userCollectAdd(mGameId, type = 0)
            } else checkLogin {
                mViewModel.userCollectDel(mGameId, type = 0)
            }
        }
        //点评
        mViewBinding.tvGameDetailsDiscuss.setOnClickAntiShakeListener {
            val gameId = mViewModel.gameDetailsLiveData.value
                ?.data?.data?.id ?: return@setOnClickAntiShakeListener
            val gameName = mViewModel.gameDetailsLiveData.value
                ?.data?.data?.name ?: return@setOnClickAntiShakeListener
            toDiscussIssueActivity(gameName, gameId)
        }
        //投诉
        mViewBinding.tvGameDetailsComplaint.setOnClickAntiShakeListener {
            val gameId = mViewModel.gameDetailsLiveData.value
                ?.data?.data?.id ?: return@setOnClickAntiShakeListener
            val gameName = mViewModel.gameDetailsLiveData.value
                ?.data?.data?.name ?: return@setOnClickAntiShakeListener
            toMineFeedbackActivity(gameName, gameId)
        }

        mViewBinding.flGameDetailsDownload.setOnClickAntiShakeListener {
            val details = mViewModel.gameDetailsLiveData.value?.data?.data
                ?: return@setOnClickAntiShakeListener
            if (details.system_type == "2") {
                toGameH5Activity(details.name, details.icon, details.id)
            } else {
                if (GT_CHANNEL != GT_CHANNEL_DEFAULT) {
                    if (!checkLogin()) {
                        toAccessActivity()
                        return@setOnClickAntiShakeListener
                    }
                }
                val download = mGameDownload
                if (download == null) {
                    val gid = details.id
                        ?: return@setOnClickAntiShakeListener
                    val gName = details.name
                        ?: return@setOnClickAntiShakeListener
                    val gIcon = details.icon
                        ?: return@setOnClickAntiShakeListener
                    val gAurl = if (!details.aurl.isNullOrEmpty()) {
                        details.aurl
                    } else {
                        return@setOnClickAntiShakeListener
                    }
                    mDownloadManager.download(gid, gName, gIcon, gAurl)
                } else if (download.downStatus == 1 || download.downStatus == 3) {
                    mDownloadManager.download(
                        gameId = download.gameId, gameName = download.gameName,
                        gameIcon = download.gameIcon, downPath = download.downPath
                    )
                } else if (download.downStatus == 2) {
                    AppUtils.installApp(download.localPath)
                } else if (download.downStatus == 4) {
                    val packageName = AppUtils.getApkInfo(download.localPath)
                        ?.packageName ?: return@setOnClickAntiShakeListener
                    AppUtils.launchApp(packageName)
                } else {
                    mDownloadManager.stopDownload(download.gameId)
                }
            }
        }

        mViewBinding.pvGameDetailsPlayer.findViewById<CheckBox>(R.id.exo_volume)
            .setOnCheckedChangeListener { _, isChecked ->
                mSimpleExoPlayer?.volume = if (isChecked) 1f else 0f
            }
    }

    override fun initData() {
        mViewModel.gameDetails(gid = mGameId)
        mViewModel.userService()
    }

    override fun initViewMode() {
        mViewModel.gameDetailsLiveData.observe(this as LifecycleOwner, { response ->
            mViewBinding.mslMultiStateLayout.setLoadingStatus(response)
            if (response.status != Status.SUCCESS)
                return@observe
            val gameDetails: GameDetails = response.data?.data
                ?: return@observe
            fillData(gameDetails)
        })

        mViewModel.userCollectAddLiveData.observe(this as LifecycleOwner, { response ->
            if (response.status == Status.FAILURE) {
                toast(response.error?.msg)
            }
            if (response.status != Status.SUCCESS)
                return@observe
            mViewModel.gameDetailsLiveData.value?.data?.data?.apply {
                this.shoucang = 1
            }
            setDrawableTopCollect(R.drawable.ic_10002)
            toast(response.data?.message)
        })

        mViewModel.userCollectDelLiveData.observe(this as LifecycleOwner, { response ->
            if (response.status == Status.FAILURE) {
                toast(response.error?.msg)
            }
            if (response.status != Status.SUCCESS)
                return@observe
            mViewModel.gameDetailsLiveData.value?.data?.data?.apply {
                this.shoucang = 0
            }
            setDrawableTopCollect(R.drawable.ic_10001)
            toast(response.data?.message)
        })

        AppFlowBus.observe(this as LifecycleOwner, Download::class.java, Observer<Download> {
            if (it.action == Download.Action.ACTION_DELETE) {
                fillProgress(download = null)
            } else {
                val gamDownload = it.gameDownload
                    ?: return@Observer
                if (gamDownload.gameId != mGameId)
                    return@Observer
                fillProgress(gamDownload)
            }
        })
    }

    override fun onResume() {
        super.onResume()
        mDownloadManager.initData()

        if (mSimpleExoPlayer?.isPlaying != true) {
            mSimpleExoPlayer?.play()
        }
    }

    override fun onPause() {
        super.onPause()
        mSimpleExoPlayer?.pause()
    }

    override fun onDestroy() {
        super.onDestroy()
        mSimpleExoPlayer?.release()
    }

    private fun fillProgress(download: GameDownload?) {

        mViewBinding.tvGameDetailsDownloadText.text = when (download?.downStatus) {
            -1 -> "等待"
            0 -> "暂停(${download.progress}%)"
            1 -> "继续(${download.progress}%)"
            2 -> "安装"
            4 -> "打开"
            else -> "下载"
        }

        mViewBinding.pbGameDetailsDownloadProgress
            .progress = download?.progress ?: 100
    }

    @SuppressLint("UseCompatLoadingForDrawables")
    private fun setDrawableTopCollect(@DrawableRes id: Int) {
        val top = resources.getDrawable(id, null)
        top.setBounds(0, 0, top.minimumWidth, top.minimumHeight)
        mViewBinding.tvGameDetailsCollect.setCompoundDrawables(null, top, null, null)
    }

    private fun fillData(gd: GameDetails) {
        mViewBinding.ivGameDetailsImage.loadImage(
            src = gd.image ?: R.mipmap.ic_80003,
            R.mipmap.ic_80003,
            R.mipmap.ic_80003
        )

        mViewBinding.ivGameDetailsImage.visibility = if (gd.video.isNullOrEmpty())
            View.VISIBLE else View.GONE
        if (!gd.video.isNullOrEmpty()) {
            if (mSimpleExoPlayer == null) {
                mSimpleExoPlayer = SimpleExoPlayer.Builder(this).build()
                mSimpleExoPlayer?.repeatMode = REPEAT_MODE_ALL
                mSimpleExoPlayer?.volume = 0f
                mViewBinding.pvGameDetailsPlayer.player = mSimpleExoPlayer
            }
            val uri = Uri.parse(gd.video)
            val mediaItem: MediaItem = MediaItem.fromUri(uri)
            mSimpleExoPlayer?.setMediaItem(mediaItem)
            mSimpleExoPlayer?.prepare()
            mSimpleExoPlayer?.play()
        }

        mViewBinding.includeGameDetails1.ivGame1Icon.loadImage(
            src = gd.icon ?: R.mipmap.ic_80008,
            R.mipmap.ic_80008,
            R.mipmap.ic_80008
        )
        mViewBinding.includeGameDetails1.tvGame1Name.text = gd.name
        mViewBinding.includeGameDetails1.tvGame1Type.text = StringBuilder().append(gd.type)
            .append("\t·\t").append(gd.number).append("次下载")
        mViewBinding.includeGameDetails1.rvGame1LabelBody.apply {
            val layoutManager = LinearLayoutManager(context).apply {
                orientation = LinearLayoutManager.HORIZONTAL
            }
            this.layoutManager = layoutManager
        }.adapter = GameListLabelAdapter().apply {
            setNewInstance(gd.biaoqian.toMutableList())
        }

        fillProgress(mGameDownload)

        if (gd.system_type == "2") {
            mViewBinding.tvGameDetailsDownloadText.text = "打开游戏"
        } else if (gd.aurl.isNullOrEmpty()) {
            mViewBinding.pbGameDetailsDownloadProgress
                .progress = 0
        }

        setDrawableTopCollect(if (gd.shoucang == 1) R.drawable.ic_10002 else R.drawable.ic_10001)
    }
}